<template>
  <el-drawer
    v-model="visible"
    title="智能助手"
    direction="rtl"
    size="520px"
    :with-header="true"
    class="chat-drawer"
    @close="handleClose"
  >
    <div class="chat-panel h-full flex flex-col">
      <!-- 聊天头部 -->
      <div class="chat-header flex items-center justify-between px-4 py-3 border-b border-gray-200/50 bg-blue-50 dark:bg-gray-800 backdrop-blur-sm">
        <div class="flex items-center gap-3">
          <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center shadow-sm border border-blue-200">
            <el-icon class="text-blue-600 text-lg">
              <ChatDotRound />
            </el-icon>
          </div>
          <div>
            <h3 class="text-[16px] font-semibold text-gray-800 dark:text-gray-100 leading-5">智能助手</h3>
            <p class="text-[13px] text-gray-500 dark:text-gray-400 leading-4 flex items-center gap-1">
              <span class="w-2 h-2 bg-green-400 rounded-full animate-pulse"></span>
              DeepSeek AI
            </p>
          </div>
        </div>
        <div class="flex items-center gap-2">
          <el-button size="small" text @click="clearChat" :disabled="messages.length <= 1" class="action-btn">
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
          <el-button size="small" text @click="handleClose" class="action-btn">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
        </div>
      </div>

      <!-- 聊天消息区域 -->
      <div ref="messagesContainer" class="chat-messages flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50/30 dark:bg-gray-900">
        <!-- 动态消息列表 -->
        <div v-for="(message, index) in messages" :key="index" class="message animate-fade-in" :class="message.role === 'user' ? 'user-message' : 'ai-message'">
          <div class="message-avatar" v-if="message.role === 'ai'">
                      <div class="w-9 h-9 rounded-full bg-blue-50 flex items-center justify-center shadow-sm border border-blue-100">
            <el-icon class="text-blue-500 text-sm">
              <ChatDotRound />
            </el-icon>
          </div>
          </div>
          <div class="message-content">
            <div class="message-bubble" :class="message.role === 'user' ? 'user-bubble' : 'ai-bubble'">
              <div v-if="message.role === 'ai' && message.content" class="prose prose-slate max-w-none" v-html="renderMarkdown(message.content)"></div>
              <div v-else-if="message.role === 'ai' && !message.content" class="typing-indicator flex space-x-1">
                <div class="w-2 h-2 bg-blue-400 rounded-full animate-bounce"></div>
                <div class="w-2 h-2 bg-blue-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                <div class="w-2 h-2 bg-blue-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
              </div>
              <p v-else class="text-gray-800 dark:text-gray-100">{{ message.content }}</p>
            </div>
            <div class="message-actions mt-2 flex items-center space-x-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
              <span class="message-time text-xs text-gray-400 dark:text-gray-500">{{ formatTime(message.timestamp) }}</span>
              <!-- 复制（仅AI消息显示） -->
              <el-button v-if="message.role === 'ai'" size="small" text @click="copyMessage(message.content)" class="action-btn-small">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
              <!-- 删除（AI与用户消息都显示） -->
              <el-button size="small" text @click="onDeleteMessage(index)" class="action-btn-small">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          <div class="message-avatar" v-if="message.role === 'user'">
                      <div class="w-9 h-9 rounded-full bg-gray-50 flex items-center justify-center shadow-sm border border-gray-200">
            <el-icon class="text-gray-500 text-sm">
              <User />
            </el-icon>
          </div>
          </div>
        </div>
      </div>

      <!-- 聊天输入区域 -->
      <div class="chat-input p-4 border-t border-gray-200/50 bg-white dark:bg-gray-800">
        <div class="flex items-end space-x-3">
          <div class="flex-1">
            <el-input
              v-model="messageText"
              type="textarea"
              :rows="3"
              placeholder="输入你的问题，Enter 发送，Shift + Enter 换行..."
              @keydown.enter.exact.prevent="sendMessage"
              resize="none"
              class="message-input"
              :disabled="isSending"
            />
          </div>
          <el-button
            type="primary"
            size="default"
            :icon="Promotion"
            @click="sendMessage"
            :loading="isSending"
            :disabled="!messageText.trim()"
            class="send-btn"
          >
            发送
          </el-button>
        </div>
        <div class="flex items-center justify-between mt-3 text-xs text-gray-500 dark:text-gray-400">
          <span class="flex items-center gap-2">
            <span class="flex items-center gap-1">
              <el-icon class="text-xs"><InfoFilled /></el-icon>
              智能对话
            </span>
          </span>
          <span :class="messageText.length > 1800 ? 'text-red-500' : 'text-gray-400'">{{ messageText.length }}/2000</span>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ChatDotRound, Delete, Close, CopyDocument, Promotion, User, InfoFilled } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue'])

// 响应式数据
const visible = ref(false)
const messageText = ref('')
const isSending = ref(false)
const isTyping = ref(false)
const messagesContainer = ref(null)

// 消息列表
const messages = ref([
  {
    role: 'ai',
    content: '你好！我是智能助手，有什么可以帮助你的吗？',
    timestamp: new Date()
  }
])

// 监听visible变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
  if (newVal) {
    scrollToBottom()
  }
})

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 方法
const handleClose = () => {
  visible.value = false
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const formatTime = (timestamp) => {
  const now = new Date()
  const diff = now - timestamp
  const minutes = Math.floor(diff / 60000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}小时前`
  
  return timestamp.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 基础 Markdown 渲染（轻量实现，支持常见格式）
const renderMarkdown = (raw) => {
  if (!raw) return ''
  // 1) 先转义 HTML，防止注入
  let text = String(raw)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\"/g, '&quot;')
    .replace(/'/g, '&#39;')

  // 2) 代码块 ```
  text = text.replace(/```([\s\S]*?)```/g, (m, p1) => {
    return `<pre class="md-code"><code>${p1.replace(/\n/g, '<br/>')}</code></pre>`
  })

  // 3) 行内代码 `code`
  text = text.replace(/`([^`]+)`/g, '<code class="md-inline">$1</code>')

  // 4) 粗体、斜体
  text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
  text = text.replace(/\*([^*]+)\*/g, '<em>$1</em>')

  // 5) 标题（仅处理 # 和 ##）
  text = text.replace(/^##\s+(.+)$/gm, '<h3>$1</h3>')
  text = text.replace(/^#\s+(.+)$/gm, '<h2>$1</h2>')

  // 6) 无序列表（- 或 * 开头的行）
  const lines = text.split(/\n/) 
  let out = []
  let inList = false
  for (const line of lines) {
    if (/^\s*[-*]\s+/.test(line)) {
      if (!inList) {
        out.push('<ul class="md-list">')
        inList = true
      }
      out.push(`<li>${line.replace(/^\s*[-*]\s+/, '')}</li>`) 
    } else {
      if (inList) {
        out.push('</ul>')
        inList = false
      }
      out.push(line)
    }
  }
  if (inList) out.push('</ul>')
  text = out.join('\n')

  // 7) 段落换行
  text = text.replace(/\n{2,}/g, '<br/><br/>')
  text = text.replace(/\n/g, '<br/>')

  return text
}

const sendMessage = async () => {
  const text = messageText.value.trim()
  if (!text || isSending.value) return
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: text,
    timestamp: new Date()
  })
  
  messageText.value = ''
  isSending.value = true
  isTyping.value = false  // 不再需要单独的闪烁指示器
  
  try {
    // 调用后端流式聊天接口
    const res = await fetch('http://localhost:8080/api/ai/chat/send-stream', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: text })
    })

    if (!res.ok) {
      throw new Error(`网络错误: ${res.status}`)
    }

    // 创建 AI 消息占位符
    const aiMessageIndex = messages.value.length
    messages.value.push({
      role: 'ai',
      content: '',
      timestamp: new Date()
    })

    // 处理流式响应
    const reader = res.body.getReader()
    const decoder = new TextDecoder()
    
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      
      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')
      
      for (const line of lines) {
        if (line.startsWith('event:')) {
          const eventName = line.substring(6).trim()
          continue
        }
        
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim()
          
          // 处理不同类型的事件
          if (data === '开始生成回复...') {
            // 开始事件，可以显示加载状态
            continue
          } else if (data === '生成完成') {
            // 完成事件
            continue
          } else if (data.startsWith('AI服务暂时不可用') || data.startsWith('聊天服务异常')) {
            // 错误事件
            throw new Error(data)
          } else if (data) {
            // 增量内容，追加到 AI 消息
            messages.value[aiMessageIndex].content += data
          }
        }
      }
    }

    ElMessage.success('消息发送成功')
  } catch (error) {
    console.error('chat error:', error)
    messages.value.push({
      role: 'ai',
      content: `请求失败：${error?.message || error}。`,
      timestamp: new Date()
    })
    ElMessage.error('发送失败，请重试')
  } finally {
    isSending.value = false
    isTyping.value = false
  }
}

const clearChat = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有聊天记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    messages.value = [
      {
        role: 'ai',
        content: '你好！我是智能助手，有什么可以帮助你的吗？',
        timestamp: new Date()
      }
    ]
    
    ElMessage.success('聊天记录已清空')
  } catch {
    // 用户取消
  }
}

const copyMessage = async (content) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('消息已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const onDeleteMessage = (idx) => {
  if (idx >= 0 && idx < messages.value.length) {
    messages.value.splice(idx, 1)
  }
}
</script>

<style scoped>
.chat-drawer :deep(.el-drawer__header) {
  padding: 0;
  border-bottom: 1px solid #e5e7eb;
  background: #3b82f6;
  color: white;
}

.chat-drawer :deep(.el-drawer__header .el-drawer__title) {
  color: white;
  font-weight: 600;
}

.chat-drawer :deep(.el-drawer__header .el-drawer__close-btn) {
  color: white;
}

.chat-drawer :deep(.el-drawer__body) {
  padding: 0;
  height: 100%;
}

.chat-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  --avatar-size: 36px; /* w-9 */
  --gap-size: 12px;
  width: 100%;
  position: relative;
}

.message:hover {
  --tw-bg-opacity: 0.02;
}

/* 用户消息保持默认左右顺序（内容在左，头像在右） */
.user-message .message-content {
  margin-left: calc(var(--avatar-size) + var(--gap-size));
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

/* AI 侧同理：垂直堆叠并靠左 */
.ai-message .message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

/* AI 消息右侧预留头像+间距，使右缘与用户气泡右缘对齐 */
.ai-message .message-content {
  margin-right: calc(var(--avatar-size) + var(--gap-size));
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
}

.message-bubble {
  word-wrap: break-word;
  line-height: 1.6;
  border-radius: 16px;
  padding: 12px 16px;
  display: inline-block;
  max-width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  position: relative;
}

.message-bubble:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 操作行对齐到对应一侧，并放在气泡下方 */
.message-actions {
  width: 100%;
}
.user-message .message-actions {
  justify-content: flex-end;
  display: flex;
}
.ai-message .message-actions {
  justify-content: flex-start;
  display: flex;
}

.user-bubble {
  background: #dbeafe;
  border: none;
  color: #1e40af;
}

.ai-bubble {
  background: white;
  border: 1px solid #e5e7eb;
  color: #374151;
}

/* 深色模式适配 */
.dark .ai-bubble {
  background: #374151;
  border-color: #4b5563;
  color: #f9fafb;
}

.message-input :deep(.el-textarea__inner) {
  border-radius: 16px;
  border: 1px solid #e2e8f0;
  resize: none;
  transition: all 0.3s ease;
  font-size: 14px;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.dark .message-input :deep(.el-textarea__inner) {
  background: #374151;
  border-color: #4b5563;
  color: #f9fafb;
}

.message-input :deep(.el-textarea__inner:focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
}

.send-btn {
  border-radius: 12px;
  padding: 8px 16px;
  transition: all 0.3s ease;
  background: #3b82f6;
  border: none;
  font-weight: 500;
}

.send-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(59, 130, 246, 0.3);
}

.send-btn:disabled {
  background: #e5e7eb;
  transform: none;
  box-shadow: none;
}

.action-btn {
  color: #6b7280;
  transition: all 0.2s ease;
}

.action-btn:hover {
  color: #374151;
  background: rgba(0, 0, 0, 0.05);
}

.dark .action-btn {
  color: #9ca3af;
}

.dark .action-btn:hover {
  color: #f9fafb;
  background: rgba(255, 255, 255, 0.1);
}

.action-btn-small {
  color: #9ca3af;
  transition: all 0.2s ease;
}

.action-btn-small:hover {
  color: #374151;
  background: rgba(0, 0, 0, 0.05);
}

.dark .action-btn-small {
  color: #6b7280;
}

.dark .action-btn-small:hover {
  color: #f9fafb;
  background: rgba(255, 255, 255, 0.1);
}

.typing-indicator .animate-bounce {
  animation: bounce 1.4s infinite ease-in-out;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fade-in 0.3s ease-out;
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

.dark .chat-messages::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
}

.dark .chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* Markdown 展示基础样式（轻量） */
.prose :where(h2) {
  font-size: 16px;
  margin: 8px 0 6px;
  font-weight: 600;
  color: #374151;
}

.dark .prose :where(h2) {
  color: #f9fafb;
}

.prose :where(h3) {
  font-size: 15px;
  margin: 6px 0 4px;
  font-weight: 600;
  color: #374151;
}

.dark .prose :where(h3) {
  color: #f9fafb;
}

.prose :where(p) {
  margin: 6px 0;
  color: #374151;
}

.dark .prose :where(p) {
  color: #f9fafb;
}

.prose :where(code.md-inline) {
  background: #f3f4f6;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 13px;
  color: #dc2626;
}

.dark .prose :where(code.md-inline) {
  background: #1f2937;
  border-color: #374151;
  color: #f87171;
}

.prose :where(pre.md-code) {
  background: #1f2937;
  color: #f9fafb;
  border-radius: 8px;
  padding: 12px;
  overflow: auto;
  border: 1px solid #374151;
  margin: 8px 0;
}

.prose :where(ul.md-list) {
  padding-left: 20px;
  margin: 8px 0;
}

.prose :where(ul.md-list li) {
  margin: 4px 0;
  color: #374151;
}

.dark .prose :where(ul.md-list li) {
  color: #f9fafb;
}

@media (max-width: 768px) {
  .chat-drawer :deep(.el-drawer) {
    width: 100% !important;
  }
  
  .message-content {
    max-width: 90%;
  }
  
  .message-bubble {
    padding: 10px 14px;
    border-radius: 14px;
  }
}
</style>
